package org.jflame.devAide.controller;

import org.jflame.commons.util.CollectionHelper;
import org.jflame.devAide.AppContext;
import org.jflame.devAide.component.CardPane;
import org.jflame.devAide.component.Note;
import org.jflame.devAide.model.NoteCatalog;
import org.jflame.devAide.plugin.PluginFactory;
import org.jflame.devAide.plugin.ToolPlugin;
import org.jflame.devAide.service.DbService;
import org.jflame.devAide.service.ThreadService;
import org.jflame.devAide.util.UIUtils;

import java.sql.SQLException;
import java.util.List;

import org.controlsfx.control.StatusBar;
import org.controlsfx.glyphfont.Glyph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.HPos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;

/**
 * 主界面
 *
 * @author yucan.zhang
 */
public class Main1Controller {

    private final Logger logger = LoggerFactory.getLogger(Main1Controller.class);

    @FXML
    private AnchorPane mainPane;
    @FXML
    private TabPane mainTab;
    @FXML
    private StatusBar statusBar;
    @FXML
    private VBox leftNavPanel;// 最左边按钮导航条
    @FXML
    private CardPane midNavPane;// 中间主要导航区
    @FXML
    private ToggleButton btnToolbox;
    @FXML
    private ToggleButton btnBook;
    @FXML
    private ToggleButton btnNote;
    @FXML
    private ToggleGroup navBtnGrp;

    @FXML
    private ListView<ToolPlugin> lstViewTool;
    @FXML
    private VBox noteCatalog;
    @FXML
    private TreeView<NoteCatalog> treeNoteCatalog;

    private ObservableList<ToolPlugin> toolPlugins = FXCollections.observableArrayList();

    private ThreadService threadService = ThreadService.instance();

    private DbService dbService;

    public Main1Controller() {
        toolPlugins.addAll(PluginFactory.getPlugins());
    }

    @FXML
    protected void initialize() {
        btnToolbox.setUserData(lstViewTool);
        initToolListView();
        // StackPane.setMargin(lstViewTool, new Insets(1));
        navBtnGrp.selectedToggleProperty()
                .addListener(new ChangeListener<Toggle>() {

                    @Override
                    public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue,
                            Toggle newValue) {
                        if (newValue != null) {
                            Node showNode = (Node) newValue.getUserData();
                            if (showNode != null) {
                                midNavPane.setShowNode(showNode);
                            }
                        }
                    }
                });

        btnToolbox.setSelected(true);

        // initKnowHomePage();
        // initMainTabEvent();

        initStatusBar();
    }

    /**
     * 初始导航主页
     */
    private void initKnowHomePage() {
        // WebEditor note = new WebEditor(ToolBarStyle.FULL);
        Note note = new Note();
        // note.setPrefSize(600, 600);
        mainTab.getTabs()
                .get(0)
                .setContent(note);
        // editor.setContent("<div>hello</div>");
        /*WebEngine webEngine = mainWebView.getEngine();
        webEngine.getLoadWorker()
                .stateProperty()
                .addListener(new ChangeListener<State>() {
        
                    @Override
                    public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
                        if (newState == Worker.State.SUCCEEDED) {
                            Text statusText = new Text(webEngine.getTitle());
                            statusBar.getLeftItems()
                                    .add(statusText);
        
                        }
                    }
                });
        webEngine.load("http://www.hao123.com");*/
        // AppContext.getInstance().getApplication().getHostServices().showDocument("https://www.hao123.com");调用系统浏览器打开网页

    }

    /*@FXML
    protected void handleEditor(ActionEvent event) {
        System.out.println(editor.getContent());
    }*/

    @FXML
    private void handleMainNav(ActionEvent event) {
        ToggleButton srcBtn = (ToggleButton) event.getSource();
        /*leftNavPanel.lookupAll(".btnNav")
                .forEach(x -> x.getStyleClass()
                        .remove("btnNavClick"));
        srcBtn.getStyleClass()
                .add("btnNavClick");*/
        if (srcBtn == btnBook) {

        } else if (srcBtn == btnNote) {
            // midNavPane.setShowNode(tmpPane);
        } else if (srcBtn == btnToolbox) {
            // showToolView();
        }

    }

    /**
     * 初始开发工具菜单列表
     */
    private void initToolListView() {
        lstViewTool.setItems(toolPlugins);
        lstViewTool.setCellFactory((ListView<ToolPlugin> l) -> new ToolListViewCell());
        lstViewTool.getSelectionModel()
                .selectedItemProperty()
                .addListener((ObservableValue<? extends ToolPlugin> ov, ToolPlugin oldPlugin, ToolPlugin newPlugin) ->
                {
                    if (newPlugin == null) {
                        return;
                    }
                    boolean isExist = false;

                    // 检查是否已经打开了，如果是直接切换过去
                    ObservableList<Tab> tabs = mainTab.getTabs();

                    for (Tab tab : tabs) {
                        if (newPlugin == tab.getUserData()) {
                            isExist = true;
                            mainTab.getSelectionModel()
                                    .select(tab);
                            break;
                        }
                    }
                    // 新生成插件界面
                    if (!isExist) {
                        Node toolPaneOpt = newPlugin.getContent();
                        Tab toolTab = new Tab(newPlugin.name());
                        toolTab.setOnCloseRequest(new EventHandler<Event>() {

                            @Override
                            public void handle(Event event) {
                                newPlugin.close();
                            }
                        });
                        /*toolTab.setOnClosed(new EventHandler<Event>() {
                        
                            @Override
                            public void handle(Event event) {
                                Tab t = (Tab) event.getSource();
                                if (lstViewTool.getSelectionModel()
                                        .getSelectedItem() == t.getUserData()) {
                                    lstViewTool.getSelectionModel()
                                            .clearSelection(lstViewTool.getSelectionModel()
                                                    .getSelectedIndex());
                                }
                            }
                        });*/

                        toolTab.setUserData(newPlugin);
                        toolTab.setGraphic(newPlugin.getIcon(12));
                        toolTab.setClosable(true);
                        toolTab.setContent(toolPaneOpt);
                        mainTab.getTabs()
                                .add(toolTab);
                        mainTab.getSelectionModel()
                                .select(toolTab);
                    }

                });

    }

    private void initStatusBar() {
        Hyperlink linkGit = new Hyperlink("源码");
        linkGit.getStyleClass()
                .add("gitlink");
        linkGit.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                AppContext.hostServices()
                        .showDocument("https://gitee.com/jqncc/dev-aide");
            }
        });

        statusBar.getRightItems()
                .add(linkGit);
    }

    /**
     * mainTab选项卡切换事件,切换左边菜单树关联切换
     */
    private void initMainTabEvent() {
        mainTab.getSelectionModel()
                .selectedItemProperty()
                .addListener(new ChangeListener<Tab>() {

                    @Override
                    public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) {
                        /*if (lstViewTool.getSelectionModel()
                                .getSelectedItem() != newValue.getUserData()) {
                            lstViewTool.getSelectionModel()
                                    .select((ToolPlugin) newValue.getUserData());
                        }*/
                    }

                });
    }

    private void initNoteCatalog() {
        dbService = new DbService();
        try {
            List<NoteCatalog> catalogs = dbService.findCataloges();
            if (CollectionHelper.isNotEmpty(catalogs)) {
                TreeItem<NoteCatalog> root = new TreeItem<NoteCatalog>(null);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    class ToolListViewCell extends ListCell<ToolPlugin> {

        private GridPane itemPane = new GridPane();
        private Label title = new Label();
        private TextFlow descTextfl;
        private Text descText = new Text();
        private boolean isRender = true;

        public ToolListViewCell() {
            itemPane.getStyleClass()
                    .add("tk-cell-pane");
            title.getStyleClass()
                    .add("tk-cell-title");
            // itemPane.setVgap(5);
            // itemPane.setGridLinesVisible(true);
            // itemPane.setMaxWidth(lstViewTool.getPrefWidth() - 20);
            // itemPane.setPrefWidth(lstViewTool.getPrefWidth() - 20);
            ColumnConstraints column1 = new ColumnConstraints();
            // column1.setHgrow(Priority.ALWAYS);
            column1.setPercentWidth(90);
            // column1.setMinWidth(150d);
            // column1.setPrefWidth(190);

            ColumnConstraints column2 = new ColumnConstraints();
            column2.setPercentWidth(10);
            column2.setPrefWidth(20);
            column2.setMaxWidth(20);
            column2.setHgrow(Priority.NEVER);
            column2.setHalignment(HPos.RIGHT);

            itemPane.getColumnConstraints()
                    .addAll(column1, column2);

            RowConstraints rowConstraints1 = new RowConstraints(24);
            itemPane.getRowConstraints()
                    .add(rowConstraints1);

            descText.setFill(Color.DARKGREY);
            descTextfl = new TextFlow(descText);
            descTextfl.setLineSpacing(3);
            descTextfl.getStyleClass()
                    .add("tk-cell-detail");

            itemPane.add(title, 0, 0);

        }

        @Override
        protected void updateItem(ToolPlugin item, boolean empty) {
            super.updateItem(item, empty);
            if (!empty && item != null) {
                // 设置完成一次后,下次不再重设,因为加载后ToolPlugin信息不变
                if (isRender) {
                    setCursor(Cursor.HAND);
                    // System.out.println(getWidth());
                    // System.out.println("title:" + title.getText());
                    title.setText(item.name());
                    Node icon = item.getIcon(14);
                    title.setGraphic(icon == null ? UIUtils.createFontGlyph("WRENCH", 14) : icon);

                    if (item.isFav()) {
                        Glyph favIco = UIUtils.createFontGlyph(org.controlsfx.glyphfont.FontAwesome.Glyph.STAR, 14);
                        favIco.setColor(Color.ORANGE);
                        itemPane.add(favIco, 1, 0);
                    }
                    if (item.getPluginInfo()
                            .getDesc() != null) {
                        descText.setText(item.getPluginInfo()
                                .getDesc());
                        itemPane.add(descTextfl, 0, 1, 2, 1);
                    }
                    isRender = false;
                }
                setGraphic(itemPane);
            } else {
                setText(null);
                setGraphic(null);
            }

        }
    }
}
